;
(function (window, angular) {
    'use strict';
    angular.module("Controller.Logistics.InfoEntry", [])
        .controller("InfoEntryCtrl", ["$scope", "ybWidget", "ybHttp", "MESG_TYPE", "$timeout", "$filter", "EventBus", "UserContextService", function ($scope, ybWidget, ybHttp, MESG_TYPE, $timeout, $filter, EventBus, UserContextService) {
            $scope.activeFlag = [true, false, false];
            $scope.markInfo = {};
            $scope.pageInfo = {
                totalPages: 1,
                totalRows: 0,
                pageSize: 10,
                curPage: 1
            };
            $scope.toolbarConfig = {
                showAdvanceSearch: false,
                showColConfig: false
            };
            $scope.condition = {};
            $scope.dataList = [];
            $scope.tableConfig = {
                fixedWidth: 130,
                scrollWidth: 1100,
                tableCol: [
                    {
                        type: "",
                        name: "物流运单号",
                        dataField: "wayBillNo",
                        clickFn: "viewDetail",
                        width: 180,
                        isShow: true,
                        isFixed: false,
                    },
                    {
                        type: "",
                        name: "客户编码",
                        dataField: "dealerOrgId",
                        width: 140,
                        isShow: true,
                        isFixed: false,
                    },
                    {
                        type: "",
                        name: "客户名称",
                        dataField: "dealerOrgName",
                        width: 150,
                        isShow: true,
                        isFixed: false,
                    },
                    {
                        type: "",
                        name: "物流状态",
                        dataField: "logisticStatusShow",
                        width: 100,
                        isShow: true,
                        isFixed: false,
                    },
                    {
                        type: "",
                        name: "收货人",
                        dataField: "receiverName",
                        width: 100,
                        isShow: true,
                        isFixed: false,
                    },
                    {
                        type: "",
                        name: "预计到达时间",
                        dataField: "expectArrivalTimeShow",
                        width: 130,
                        isShow: true,
                        isFixed: false,
                    },
                    {
                        type: "",
                        name: "单据类型",
                        dataField: "businessTypeShow",
                        width: 100,
                        isShow: true,
                        isFixed: false,
                    },
                    {
                        type: "",
                        name: "发运方式",
                        dataField: "shippingMethod",
                        width: 100,
                        isShow: true,
                        isFixed: false,
                    },
                    {
                        type: "",
                        name: "承运商",
                        dataField: "carrierOrgName",
                        width: 100,
                        isShow: true,
                        isFixed: false,
                    },
                    {
                        type: "",
                        name: "备注",
                        dataField: "remark",
                        width: 130,
                        isShow: true,
                        isFixed: false,
                    },
                    {
                        type: "",
                        name: "制单人",
                        dataField: "createUserName",
                        width: 130,
                        isShow: true,
                        isFixed: false,
                    },
                    {
                        type: "",
                        name: "制单时间",
                        dataField: "createDateShow",
                        width: 130,
                        isShow: true,
                        isFixed: false,
                    },
                    {
                        type: "operate",
                        name: "操作",
                        dataField: "",
                        isShow: true,
                        isFixed: true,
                    }
                ]
            };

            $scope.detailInfo = {};
            $scope.logisticsNew = { showDate: true };

            $scope.setFixedWidth = function () {
                $scope.tbStyle = {scrollLeft: {left: $scope.tableConfig.fixedWidth + "px"}};
            };

            $scope.checkDate = function (obj, startFiled, endFiled) {
                var timeFormatObj = ybWidget.CheckDate(obj[startFiled], obj[endFiled]);
                if (!!timeFormatObj.tStart) {
                    obj[startFiled] = timeFormatObj.tStart;
                }
                if (!!timeFormatObj.tEnd) {
                    obj[endFiled] = timeFormatObj.tEnd;
                }
            };

            $scope.changeTab = function (index) {
                $scope.activeFlag = [false, false, false];
                $scope.activeFlag[index] = true;
                switch (index) {
                    case 0:
                        initData();
                        break;
                    case 1:
                        break;
                    case 2:
                        break;
                    default:
                        break;
                }
            };

            function initData() {
                $scope.detailInfo = {};
                $scope.logisticNodes = [];
                $scope.logisticsNew = { showDate: true };
                $scope.showSync = false;
            }

            function getDataList(curPage) {
                var service = "device";
                var reqUrl = "/logisticStatus/logisticListing";
                var param = {};
                if (!!curPage) {
                    $scope.pageInfo.curPage = curPage;
                }
                param.pageSize = $scope.pageInfo.pageSize;
                param.pageNum = $scope.pageInfo.curPage;
                param.filters = angular.copy($scope.condition);
                ybHttp.Post(service, reqUrl, param).then(function (resp) {
                    if (resp.code !== 0) {
                        ybWidget.ShowMessage(resp, MESG_TYPE.Error);
                        return;
                    }
                    angular.forEach(resp.value.list, function (item) {
                        item.businessTypeShow = $filter("BusinessType")(item.businessType);
                        item.logisticStatusShow = $filter("ProgressStatus")(item.logisticStatus, "logisticStatus");
                        item.expectArrivalTimeShow = $filter("YbDate")(item.expectArrivalTime, "yyyy-MM-dd hh:mm:ss");
                        item.createDateShow = $filter("YbDate")(item.createDate, "yyyy-MM-dd hh:mm:ss");
                    });
                    $scope.pageInfo.totalRows = resp.value.total;
                    $scope.pageInfo.totalPages = resp.value.pages;
                    $scope.dataList = resp.value.list;
                });
            }

            $scope.switchToolbar = function (toolbar) {
                if (!!$scope.toolbarConfig["show" + toolbar]) {
                    $scope.toolbarConfig["show" + toolbar] = false;
                } else {
                    $timeout(function () {
                        $scope.toolbarConfig["show" + toolbar] = true;
                    });
                }
            };

            $scope.selectRow = function (index) {
                $scope.markInfo.curRow = index
            };

            $scope.search = function (curpage) {
                getDataList(curpage);
            };

            $scope.reset = function () {
                $scope.condition = {};
            };
            
            // 打开录入物流信息tab
            $scope.handleEntryInfo = function (item) {
                $scope.currentId = item.id;

                getDataDetail().then(function() {
                    getLogistics().then(function() {
                        var dateFrame = ""; // yyyy-MM-dd (该字段存在的目的是按同一天分组)
                        if($scope.logisticNodes.length > 0){
                            dateFrame = $filter("YbDate")($scope.logisticNodes[0].createDate);
                            $scope.logisticNodes[0].showDate = true;
                        }
                        for (var i = 1, len = $scope.logisticNodes.length; i < len; i++) {
                            if ($filter("YbDate")($scope.logisticNodes[i].createDate) === dateFrame) {
                                $scope.logisticNodes[i].showDate = false;
                            } else {
                                $scope.logisticNodes[i].showDate = true;
                                dateFrame = $filter("YbDate")($scope.logisticNodes[i].createDate);
                            }
                        }
                        EventBus.Publish("setTimeShow", $scope.logisticNodes); // 物流组件初始化：已有物流数据

                        $scope.changeTab(1);
                    })
                })
            };

            function getDataDetail() {
                var service = "device";
                var reqUrl = "/logisticWayBill/viewInfo";
                var param = {
                    id: $scope.currentId
                };
                return ybHttp.Get(service, reqUrl, param).then(function (resp) {
                    if (resp.code !== 0) {
                        ybWidget.ShowMessage(resp, MESG_TYPE.Error);
                        return;
                    }
                    $scope.detailInfo = resp.value;
                });
            }
            function getLogistics() {
                var service = "device";
                var reqUrl = "/logisticStatus/logisticRecords";
                var param = {
                    wayBillId: $scope.currentId
                };
                return ybHttp.Get(service, reqUrl, param).then(function (resp) {
                    if (resp.code !== 0) {
                        ybWidget.ShowMessage(resp, MESG_TYPE.Error);
                        return;
                    }

                    angular.forEach(resp.value, function(item) {
                        item.createDate = item.recordTime;
                        item.address = item.nodeInfo;
                    })
                    $scope.logisticNodes = resp.value;
                });
            }

            // 录入物流信息
            $scope.entryLogistics = function () {
                var service = "device";
                var reqUrl = "/logisticStatus/logisticRecordEnter";
                var param = {
                    wayBillId: $scope.currentId,
                    recordTime: $scope.logisticsNew.createDate,
                    nodeInfo: $scope.logisticsNew.address
                };
                ybHttp.Post(service, reqUrl, param).then(function (resp) {
                    if (resp.code !== 0) {
                        ybWidget.ShowMessage(resp, MESG_TYPE.Error);
                        return;
                    }
                    if ($scope.logisticNodes.length > 0) {
                        var lastDataDate = new Date($scope.logisticNodes[$scope.logisticNodes.length - 1].createDate).getTime();
                        if ($filter("YbDate")($scope.logisticsNew.createDate) === $filter("YbDate")(lastDataDate)) {
                            $scope.logisticsNew.showDate = false;
                        }
                    }
                    $scope.logisticNodes.push(angular.copy($scope.logisticsNew));
                    EventBus.Publish("entryTimeFrame", $scope.logisticsNew); // 物流组件更新：新添加物流数据
                });
            };

            // 到货
            $scope.receiveGoods = function () {
                ybWidget.ShowDatePicker({name:'到货日期'}).then(function(data) {
                    var service = "device";
                    var reqUrl = "/logisticStatus/arrivalConfirm";
                    var param = {
                        wayBillId: $scope.currentId,
                        arrivalTime: $filter("YbDate")(data, "yyyy-MM-dd")
                    };
                    ybHttp.Post(service, reqUrl, param).then(function (resp) {
                        if (resp.code !== 0) {
                            ybWidget.ShowMessage(resp, MESG_TYPE.Error);
                            return;
                        }
                        ybWidget.ShowToaster('success', '操作成功');
                        getDataList()
                        $scope.changeTab(0);
                    });
                })
            };

            // 签收
            $scope.handleSign = function(item) {
                ybWidget.ShowMessage("确定要签收吗？", MESG_TYPE.Ask).then(function () {
                    var service = "device";
                    var reqUrl = "/logisticStatus/signConfirm";
                    var param = {
                        wayBillId: item.id
                    };
                    ybHttp.Get(service, reqUrl, param).then(function (resp) {
                        if (resp.code !== 0) {
                            ybWidget.ShowMessage(resp, MESG_TYPE.Error);
                            return;
                        }
                        ybWidget.ShowToaster('success', '操作成功');
                        getDataList();
                    });
                }, function() {})
            };

            $scope.tdClick = function (item, fnType) {
                switch (fnType) {
                    case "viewDetail":
                        viewDetail(item);
                        break;
                    default:
                        break;
                }
            };

            function viewDetail(item) {
                $scope.currentId = item.id;
                
                getDataDetail().then(function() {
                    $scope.needShowSync = $scope.detailInfo.headInfo.shippingMethodId == '0004' || $scope.detailInfo.headInfo.shippingMethodId == '0007'
                    $scope.changeTab(2);
                })
            }

            // 详情页点击物流信息tab
            $scope.handleClickLogistics = function() {
                getLogistics()
            };

            // 同步 德邦、顺丰的物流信息
            $scope.syncLogistics = function() {
                var service = "device";
                var reqUrl = "/logisticStatus/synLogisticInfo";
                var param = {
                    wayBillId: $scope.currentId
                };
                ybHttp.Get(service, reqUrl, param).then(function (resp) {
                    if (resp.code !== 0) {
                        ybWidget.ShowMessage(resp, MESG_TYPE.Error);
                        return;
                    }
                    ybWidget.ShowToaster('success', '操作成功');
                    getLogistics();
                });
            };

            var btnPermissionCode = {
                logisticStatusEnterRecord: window.ActionCode.logisticStatusEnterRecord,
                logisticStatusSign: window.ActionCode.logisticStatusSign,
                logisticStatusSync: window.ActionCode.logisticStatusSync,
                logisticStatusArrival: window.ActionCode.logisticStatusArrival,
            };

            $scope.btnPermission = {
                logisticStatusEnterRecord: true,
                logisticStatusSign: true,
                logisticStatusSync: true,
                logisticStatusArrival: true,
            };

            function setBtnPermission() {
                for (var key in btnPermissionCode) {
                    $scope.btnPermission[key] = UserContextService.CheckPermission([btnPermissionCode[key]]);
                }
            }

            (function () {
                getDataList();
                $scope.setFixedWidth();
                UserContextService.SetBtnPermission(setBtnPermission);
            })();
        }])
    ;
})(window, window.angular);
